<template>
  <div class="article-container">
    <el-card class="box-card">
      <el-button type="primary" @click="dialogVisible = true" >添加品牌</el-button >
      <el-button type="danger" @click="deleteClick">批量删除</el-button>
      <!-- 表格 -->
      <el-table
        :data="brandList"
        style="width: 100%"
        stripe
        row-key="id"
        default-expand-all
        :tree-props="{ children: 'children' }"
        lazy
        @selection-change="handleSelectionChange"
        >>
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="logo" label="品牌logo"> 
          <template v-slot="slot">
             <el-image style=" height: 40px" :src="slot.row.logo" fit="contain">
              <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline"></i>
            </div>
             </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="品牌名称"> </el-table-column>
        <el-table-column label="描述"> 
           <template v-slot="slot">
            <div class="desc">{{slot.row.desc}}</div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80" align="center">
          <template v-slot="slot">
            <el-tag type="success" v-if="slot.row.status">显示</el-tag>
            <el-tag v-else>隐藏</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="mall_category.name" label="所属类目" align="center">
        </el-table-column>
        <el-table-column  label="操作" align="center">
          <template v-slot="slot">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="small"
              @click="editClick(slot.row)"
              >编辑</el-button >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="deleteClick(slot.row)"
              >删除</el-button >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <el-dialog
        :title="title"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="close"
        @close="close"
      >
        <el-form ref="form" :model="form" label-width="85px">
          <el-form-item label="品牌LOGO">
          <el-image  style=" height: 40px" :src="form.logo" fit="contain">
            <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
          <el-upload
          :headers="uploadHeaders"
            action="http://127.0.0.1:8001/api/admin/upload/"
            :on-success="onSuccess"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :multiple="false"
            :limit="1"
            :on-exceed="handleExceed" >
            <el-button size="small" type="primary">{{form.logo ? '重新上传':'上传logo'}}</el-button>
          </el-upload>
          </el-form-item>
          <el-form-item label="品牌名称">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="所属类目">
            <!-- <el-input v-model="form.category_id"></el-input> -->
             <el-cascader
             v-model="form.category_id"
             @focus="focus"
              :options="categoryList"
              :props="props"
               @change="handleChange"
              clearable></el-cascader>
          </el-form-item>
          <el-form-item label="品牌描述">
            <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4}"
              v-model="form.desc">
            </el-input>
          </el-form-item>
          <el-form-item label="类目状态">
            <el-switch
              v-model="form.status"
              active-text="显示"
              inactive-text="隐藏"
            >
            </el-switch>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible=false">取 消</el-button>
          <el-button type="primary" @click="addClick">确 定</el-button>
        </span>
      </el-dialog>

     
    </el-card>
  </div>
</template>

<script>
import { getToken} from '@/utils/auth'
import { toTree } from "@/utils";
import { getCategoryList} from "@/api/admin/mall_Category";
import {
  getBrandList,
  deleteBrand,
  addBrand,
  editBrand
} from "@/api/admin/mall_Brand";
// import { mapGetters } from "vuex";
export default {
  name: "Brand",
  components: { },
  data() {
    return {
      props:{ 
        checkStrictly: true,
        value:'id',
        label: 'name',
        children:'children',
        emitPath:false
      },
      dialogVisible: false,
      brandList: [], // 表格数据
      queryInfo: {
        query: "", // 查询参数
        pageNum: 1, // 分页页码
        pageSize: 10, // 页面数据条数
      },
      total: 0,
      selectRows: [], // 全选数据
      title: "新增品牌",
      form: {
        category_id : "",
        name: "",
        logo:'',
        desc:'',
        status: true,
      },
      optionProps: {
        value: "id",
        label: "name",
        children: "children",
        // expandTrigger: "hover",
        checkStrictly: true,
        emitPath: false,
        expandTrigger: 'hover'
      },
      // 设置请求头
        uploadHeaders:{
          Authorization:`Bearer ${getToken()}`
        },
        categoryList:[]
    };
  },
  created() {
    this.getBrandList();
  },
  methods: {
     async getCategoryList() {
      const { list} = await getCategoryList({pageSize:100});
      this.categoryList = toTree(list);
    },
    // 表格数据
    async getBrandList() {
      const { list, pageNum, pageSize, total } = await getBrandList(this.queryInfo);
      this.brandList = list;
      this.queryInfo.pageNum = Number(pageNum);
      this.queryInfo.pageSize = Number(pageSize);
      this.total = total;
    },
    // 设置页面数据条数
    handleSizeChange(val) {
      this.queryInfo.pageSize = val;
      this.getBrandList();
    },
    // 设置分页页码
    handleCurrentChange(val) {
      this.queryInfo.pageNum = val;
      this.getBrandList();
    },
    // 编辑
    editClick(row) {
      this.title = '编辑品牌'
       this.form = {
        id: row.id,
         category_id :row.category_id,
         logo: row.logo,
        name: row.name,
        desc: row.desc,
        status: row.status,
      };
       this.dialogVisible =true
    },
    // 添加
    async addClick() {
      if(this.form.id){
        await editBrand(this.form.id,this.form)
      }else{
        await addBrand(this.form);
        this.form = {
          category_id:'',
          logo:'',
          name: "",
          desc:'',
          status: true,
        };
      }
      this.$message.success(`${this.form.id ? '修改' : '添加'}品牌${this.form.name}成功`);
      this.dialogVisible = false;
      this.getBrandList();
    },
    // 关闭弹层后
    close(){
      this.title = '新增品牌'
      this.form = {
        category_id:'',
        name: "",
        logo:'',
        parentId: 0,
        status: true,
      };
      this.dialogVisible = false;
    },
    // 删除用户
    deleteClick(row) {
      if (row.id) {
        this.$confirm("你确定要删除选中项吗", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            await deleteBrand({ ids: [row.id] });
            this.getBrandList();
            this.$message.success("删除成功");
          })
          .catch(() => {
            this.$message.info("已取消删除");
          });
      } else {
        // 批量删除
        if (!this.selectRows.length)
          return this.$message.warning("请选择要删除的选中项");
        const ids = this.selectRows.map((item) => item.id);
        this.$confirm("你确定要删除选中项吗", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            await deleteBrand({ ids });
            this.getBrandList();
            this.$message.success("删除成功");
          })
          .catch(() => {
            this.$message.info("已取消删除");
          });
      }
    },
    // 全选数据
    handleSelectionChange(val) {
      this.selectRows = val;
    },
    // 移除图片后的操作
    handleRemove(file, fileList) {
        // console.log(file, fileList);
        this.form.logo=''
      },
      // 上传图片成功
      onSuccess(response, file, fileList) {
        this.form.logo = response.data.file
      },
      // 提示限制文件个数
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      // 提示是否移除图片
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      handleChange(value) {
        this.form.category_id = value
        console.log(value);
      },
      focus(event){
        this.getCategoryList()
      },
  },
};
</script>

<style lang="scss">
.el-select .el-input {
  width: 80px;
}
.box-card {
  margin: 20px;
}
.el-table {
  margin: 20px 0px;
}
.el-image {
  border-radius: 5px;
}
.desc{
    display:-webkit-box;
  -webkit-line-clamp:2;
  -webkit-box-orient:vertical;
  overflow:hidden;
}
</style>
